﻿using System.Collections.Generic;

namespace eslib.nnp5.layers
{
    /// <summary>
    /// 传输层数据包基类
    /// </summary>
    public abstract class TransportPKGBase
    {

        #region FF转义

        internal static byte[] head = { 0xff, 0x01 };        //包头
        internal static byte[] tail = { 0xff, 0x02 };        //包尾
        internal static byte[] FF = { 0xff, 0x00 };      //0xff转义标识


        /// <summary>
        /// FF转义
        /// </summary>
        /// <param name="buffer">原始数据</param>
        internal static List<byte> ffTransData(List<byte> buffer)
        {
            List<byte> res = new List<byte>();

            for (int i = 0; i < buffer.Count; i++)
            {
                byte b = buffer[i];
                if (b == 0xff)
                {
                    res.AddRange(FF);
                }
                else
                {
                    res.Add(b);
                }
            }

            //转义后数据段长度检查
            if (res.Count > 2147483647) throw new TransportLayerException("数据段过长(不能超过2G)");

            return res;
        }

        #endregion



        /// <summary>
        /// 获取带包头包尾的缓存
        /// </summary>
        /// <returns></returns>
        public abstract byte[] makePKG();



        /// <summary>
        /// 包ID
        /// </summary>
        protected uint pkgID;

        /// <summary>
        /// 设置包ID
        /// </summary>
        /// <param name="id"></param>
        public void setPkgID(uint id)
        {
            pkgID = id;
        }

        /// <summary>
        /// 获取包ID
        /// </summary>
        /// <returns></returns>
        public uint getPkgID()
        {
            return pkgID;
        }

    }
}